package com.food.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.food.dao.service.GradeService;
import com.food.model.Grade;
import com.food.model.Member;

/**
 * Servlet implementation class GradeServlet
 */
@WebServlet("/recipe/GradeServlet")
public class GradeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{
		GradeService service = new GradeService(); 
		HttpSession session = request.getSession();
		Member member = (Member)session.getAttribute("user");
		int rid = Integer.parseInt(request.getParameter("rid"));
		int gscore = Integer.parseInt(request.getParameter("gscore"));
		Grade grade = new Grade();
		grade.setRid(rid);
		grade.setGscore(gscore);
		grade.setMbid(member.getMbid());
		
		List<Grade> list =  service.findGradeByRecipe(grade);
		for(Grade g:list){
			
			if(g.getMbid()==member.getMbid()){
				
				request.setAttribute("failgrade", "failgrade");
				RequestDispatcher rd = request
						.getRequestDispatcher("/recipe/ShowRecipe?rid="+rid);
				rd.forward(request, response);
				return;
			}
		}
		
		service.insertGrade(grade);
		RequestDispatcher rd = request
				.getRequestDispatcher("/recipe/ShowRecipe?rid="+rid);
		rd.forward(request, response);
		return;
	}catch(Exception e){
		RequestDispatcher rd = request
				.getRequestDispatcher("../index.jsp");
		rd.forward(request, response);
		return;
	}
		
	
	
		
	}

}
